import { useQuery, useQueryClient } from 'react-query'
import { useNavigate } from 'react-router-dom'
import { authApi, authUtils, UserResponse } from '../services/auth'

// 使用当前用户信息的hook
export const useCurrentUser = () => {
  return useQuery<UserResponse>(
    'currentUser',
    authApi.getCurrentUser,
    {
      enabled: authUtils.isAuthenticated(),
      staleTime: 5 * 60 * 1000, // 5分钟
      cacheTime: 10 * 60 * 1000, // 10分钟
      retry: false,
      onSuccess: (data) => {
        authUtils.saveUser(data)
      },
      onError: () => {
        // Token无效时清除本地存储
        authUtils.logout()
      },
    }
  )
}

// 认证状态hook
export const useAuth = () => {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const { data: user, isLoading, error } = useCurrentUser()

  const logout = () => {
    authUtils.logout()
    queryClient.clear()
    navigate('/login')
  }

  const isAuthenticated = authUtils.isAuthenticated() && !error
  const isAdmin = user?.role === 'admin'
  const hasRole = (role: string) => authUtils.hasRole(role)

  return {
    user,
    isLoading,
    isAuthenticated,
    isAdmin,
    hasRole,
    logout,
  }
}

// 权限检查hook
export const usePermission = (requiredRole?: string) => {
  const { user, isAuthenticated } = useAuth()

  if (!isAuthenticated) {
    return { hasPermission: false, reason: 'not_authenticated' }
  }

  if (!user) {
    return { hasPermission: false, reason: 'user_not_loaded' }
  }

  if (requiredRole && !authUtils.hasRole(requiredRole)) {
    return { hasPermission: false, reason: 'insufficient_role' }
  }

  return { hasPermission: true, reason: null }
}

// 登录重定向hook
export const useLoginRedirect = () => {
  const navigate = useNavigate()
  
  const redirectToLogin = (from?: string) => {
    const redirectPath = from || window.location.pathname
    navigate('/login', { 
      state: { from: redirectPath },
      replace: true 
    })
  }

  return { redirectToLogin }
}